'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { MainLayout } from '@/components/layout/main-layout'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { 
  ArrowLeft, 
  User, 
  Phone, 
  MapPin, 
  Calendar, 
  Activity, 
  Heart, 
  Zap, 
  TrendingUp,
  Clock,
  Database
} from 'lucide-react'
import { format } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar } from 'recharts'
import { HeartRateChart } from '@/components/heart-rate-echart'
import { StepChart } from '@/components/step-chart'

interface UserDetail {
  id: number
  mobile: string
  cc: number
  name: string
  avatar?: string
  gender: number
  age: number
  height: string
  weight: string
  city: string
  createTime: string
  lastActiveTime: string
  totalHealthLogs: number
  recentHealthLogs: Array<{
    id: number
    type: string
    device_id: string
    data: any
    timestamp: string
    created_at: string
  }>
  healthStats: Array<{
    type: string
    count: number
  }>
}

const healthTypeMap = {
  heart_rate: { label: '心率', icon: Heart, color: 'bg-red-100 text-red-800', unit: 'bpm' },
  temperature: { label: '体温', icon: TrendingUp, color: 'bg-orange-100 text-orange-800', unit: '°C' },
  spo2: { label: '血氧', icon: Zap, color: 'bg-green-100 text-green-800', unit: '%' },
  hrv: { label: '心率变异性', icon: Activity, color: 'bg-blue-100 text-blue-800', unit: 'ms' }
}

function UserDetailContent() {
  const params = useParams()
  const router = useRouter()
  const userId = params.id as string
  const [loading, setLoading] = useState(true)
  const [userDetail, setUserDetail] = useState<UserDetail | null>(null)
  const [selectedDate, setSelectedDate] = useState<string>(new Date().toISOString().split('T')[0])

  useEffect(() => {
    if (userId) {
      fetchUserDetail()
    }
  }, [userId])

  const fetchUserDetail = async () => {
    try {
      const response = await fetch(`/api/users/${userId}`)
      const result = await response.json()

      if (result.success) {
        setUserDetail(result.data)
      } else {
        alert(result.message || '获取用户详情失败')
      }
    } catch (error) {
      console.error('获取用户详情错误:', error)
      alert('获取用户详情失败，请重试')
    } finally {
      setLoading(false)
    }
  }

  const formatTime = (timeStr: string) => {
    try {
      return format(new Date(timeStr), 'yyyy-MM-dd HH:mm:ss', { locale: zhCN })
    } catch (e) {
      return '未知'
    }
  }

  const getGenderText = (gender: number) => {
    switch (gender) {
      case 1: return '男'
      case 2: return '女'
      default: return '未知'
    }
  }

  const getGenderColor = (gender: number) => {
    switch (gender) {
      case 1: return 'bg-blue-100 text-blue-800'
      case 2: return 'bg-pink-100 text-pink-800'
      default: return 'bg-gray-100 text-gray-800'
    }
  }

  const getUserInitials = (name: string) => {
    if (!name) return 'U'
    return name.length > 1 ? name.substring(0, 2) : name[0]
  }

  const formatHealthData = (type: string, data: any) => {
    try {
      switch (type) {
        case 'heart_rate':
          return `${data.onceHeartValue || data.heart_rate || data.value || '--'} bpm`
        case 'temperature':
          return `${data.temperature || data.value || '--'} °C`
        case 'spo2':
          return `${data.spo2 || data.value || '--'} %`
        case 'hrv':
          return `${data.hrv || data.value || '--'} ms`
        default:
          return JSON.stringify(data).substring(0, 30) + '...'
      }
    } catch (e) {
      return '--'
    }
  }

  const getHealthTypeInfo = (type: string) => {
    return healthTypeMap[type as keyof typeof healthTypeMap] || { 
      label: type, 
      icon: Activity, 
      color: 'bg-gray-100 text-gray-800',
      unit: ''
    }
  }

  if (loading) {
    return (
      <div className="p-6">
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
            <p className="mt-2 text-gray-500">加载用户详情中...</p>
          </div>
        </div>
      </div>
    )
  }

  if (!userDetail) {
    return (
      <div className="p-6">
        <div className="text-center py-12">
          <User className="w-12 h-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">用户不存在</h3>
          <p className="text-gray-500 mb-4">未找到该用户的详细信息</p>
          <Button onClick={() => router.back()}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
        </div>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题和返回按钮 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="outline" onClick={() => router.back()}>
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
          <div>
            <h1 className="text-2xl font-semibold text-gray-900">用户详情</h1>
            <p className="text-sm text-gray-500 mt-1">查看用户的详细信息和健康数据</p>
          </div>
        </div>
      </div>

      {/* 用户基本信息 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle className="flex items-center">
              <User className="w-5 h-5 mr-2" />
              基本信息
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 头像和姓名 */}
            <div className="text-center">
              <Avatar className="w-20 h-20 mx-auto mb-4">
                <AvatarImage src={userDetail.avatar} alt={userDetail.name} />
                <AvatarFallback className="bg-blue-100 text-blue-600 text-xl">
                  {getUserInitials(userDetail.name)}
                </AvatarFallback>
              </Avatar>
              <h3 className="text-lg font-semibold text-gray-900">{userDetail.name || '未设置姓名'}</h3>
              <p className="text-sm text-gray-500">ID: {userDetail.id}</p>
            </div>

            {/* 详细信息 */}
            <div className="space-y-4">
              <div className="flex items-center space-x-3">
                <Phone className="w-4 h-4 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-500">手机号</p>
                  <p className="font-medium">
                    {userDetail.mobile ? `+${userDetail.cc || 86} ${userDetail.mobile}` : '未绑定'}
                  </p>
                </div>
              </div>

              <div className="flex items-center space-x-3">
                <User className="w-4 h-4 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-500">性别</p>
                  <Badge className={getGenderColor(userDetail.gender)}>
                    {getGenderText(userDetail.gender)}
                  </Badge>
                </div>
              </div>

              {userDetail.age > 0 && (
                <div className="flex items-center space-x-3">
                  <Calendar className="w-4 h-4 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">年龄</p>
                    <p className="font-medium">{userDetail.age} 岁</p>
                  </div>
                </div>
              )}

              {userDetail.height !== '0' && userDetail.height && (
                <div className="flex items-center space-x-3">
                  <TrendingUp className="w-4 h-4 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">身高</p>
                    <p className="font-medium">{userDetail.height} cm</p>
                  </div>
                </div>
              )}

              {userDetail.weight !== '0' && userDetail.weight && (
                <div className="flex items-center space-x-3">
                  <Database className="w-4 h-4 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">体重</p>
                    <p className="font-medium">{userDetail.weight} kg</p>
                  </div>
                </div>
              )}

              {userDetail.city && (
                <div className="flex items-center space-x-3">
                  <MapPin className="w-4 h-4 text-gray-400" />
                  <div>
                    <p className="text-sm text-gray-500">城市</p>
                    <p className="font-medium">{userDetail.city}</p>
                  </div>
                </div>
              )}

              <div className="flex items-center space-x-3">
                <Calendar className="w-4 h-4 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-500">注册时间</p>
                  <p className="font-medium">{userDetail.createTime ? formatTime(userDetail.createTime) : '未知'}</p>
                </div>
              </div>

              <div className="flex items-center space-x-3">
                <Clock className="w-4 h-4 text-gray-400" />
                <div>
                  <p className="text-sm text-gray-500">最后活跃</p>
                  <p className="font-medium">{userDetail.lastActiveTime ? formatTime(userDetail.lastActiveTime) : '从未活跃'}</p>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 健康数据统计 */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle className="flex items-center">
              <Activity className="w-5 h-5 mr-2" />
              健康数据统计
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
              <div className="text-center p-4 bg-blue-50 rounded-lg">
                <Database className="w-8 h-8 text-blue-600 mx-auto mb-2" />
                <p className="text-2xl font-bold text-blue-600">{userDetail.totalHealthLogs.toLocaleString()}</p>
                <p className="text-sm text-gray-500">总记录数</p>
              </div>
              <div className="text-center p-4 bg-green-50 rounded-lg">
                <Activity className="w-8 h-8 text-green-600 mx-auto mb-2" />
                <p className="text-2xl font-bold text-green-600">{userDetail.healthStats.length}</p>
                <p className="text-sm text-gray-500">数据类型</p>
              </div>
              <div className="text-center p-4 bg-purple-50 rounded-lg">
                <Clock className="w-8 h-8 text-purple-600 mx-auto mb-2" />
                <p className="text-2xl font-bold text-purple-600">{userDetail.recentHealthLogs.length}</p>
                <p className="text-sm text-gray-500">最近记录</p>
              </div>
              <div className="text-center p-4 bg-orange-50 rounded-lg">
                <TrendingUp className="w-8 h-8 text-orange-600 mx-auto mb-2" />
                <p className="text-2xl font-bold text-orange-600">
                  {userDetail.healthStats.reduce((sum, stat) => sum + stat.count, 0).toLocaleString()}
                </p>
                <p className="text-sm text-gray-500">统计总数</p>
              </div>
            </div>

            {/* 健康数据类型分布图表 */}
            {userDetail.healthStats.length > 0 && (
              <div className="mt-6">
                <h4 className="text-lg font-medium mb-4">数据类型分布</h4>
                <ResponsiveContainer width="100%" height={300}>
                  <BarChart data={userDetail.healthStats}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis 
                      dataKey="type" 
                      tickFormatter={(value) => getHealthTypeInfo(value).label}
                    />
                    <YAxis />
                    <Tooltip 
                      labelFormatter={(value) => getHealthTypeInfo(value as string).label}
                      formatter={(value) => [value, '记录数']}
                    />
                    <Bar dataKey="count" fill="#3b82f6" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 健康数据图表 */}
      <div className="space-y-6">
        {/* 日期选择器 */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Calendar className="w-5 h-5 mr-2" />
              健康数据分析
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-center space-x-4">
              <label htmlFor="date-select" className="text-sm font-medium text-gray-700">
                选择日期:
              </label>
              <input
                id="date-select"
                type="date"
                value={selectedDate}
                onChange={(e) => setSelectedDate(e.target.value)}
                className="px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              />
            </div>
          </CardContent>
        </Card>

        {/* 心率图表 */}
        <HeartRateChart userId={userId} selectedDate={selectedDate} />

        {/* 步数图表 */}
        <StepChart userId={userId} selectedDate={selectedDate} />
      </div>

      {/* 最近健康记录 */}
      {userDetail.recentHealthLogs.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center">
              <Activity className="w-5 h-5 mr-2" />
              最近健康记录
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b">
                    <th className="text-left p-3">记录ID</th>
                    <th className="text-left p-3">数据类型</th>
                    <th className="text-left p-3">设备ID</th>
                    <th className="text-left p-3">数值</th>
                    <th className="text-left p-3">记录时间</th>
                  </tr>
                </thead>
                <tbody>
                  {userDetail.recentHealthLogs.map((log) => {
                    const typeInfo = getHealthTypeInfo(log.type)
                    const IconComponent = typeInfo.icon
                    return (
                      <tr key={log.id} className="border-b hover:bg-gray-50">
                        <td className="p-3 font-mono text-xs">{log.id}</td>
                        <td className="p-3">
                          <Badge className={typeInfo.color}>
                            <IconComponent className="w-3 h-3 mr-1" />
                            {typeInfo.label}
                          </Badge>
                        </td>
                        <td className="p-3 font-mono text-xs">{log.device_id}</td>
                        <td className="p-3 font-medium">{formatHealthData(log.type, JSON.parse(log.data || '{}'))}</td>
                        <td className="p-3 text-xs text-gray-500">
                          {format(new Date(parseInt(log.timestamp)), 'yyyy-MM-dd HH:mm:ss')}
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
            </div>
            <div className="mt-4 text-center">
              <Button 
                variant="outline" 
                onClick={() => router.push(`/health-query?mobile=${userDetail.mobile}`)}
              >
                查看更多健康记录
              </Button>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}

export default function UserDetailPage() {
  return (
    <MainLayout title="用户详情">
      <UserDetailContent />
    </MainLayout>
  )
}